package cn.dazd.exceledit.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.dazd.exceledit.entity.ExcelVo;
import cn.dazd.exceledit.mapper.ExcelVoMapper;
import cn.dazd.exceledit.service.OfficeConfig;
import cn.dazd.exceledit.utils.ExcelUtils;

/**
 * excel修改导出 TODO 上传
 * 
 * @author wangwei16
 *
 */
@RestController
public class ExcelController {
	@Autowired
	OfficeConfig officeConfig;
	@Autowired
	ExcelVoMapper excelVoMapper;

	/**
	 * 根据版本获取文件
	 * 
	 * @param id
	 * @param version
	 * @return
	 */

	@RequestMapping("getFileByVersion")
	public Object getFileByVersion(Integer id, Integer version) {
		return excelVoMapper.selectOne(new ExcelVo() {
			{
				setId(id);
				setVersion(version);
			}
		}).getContent();
	}

	/**
	 * 保存新版本
	 * 
	 * @param json
	 * @return
	 */

	@RequestMapping("save")
	public Object save(@RequestBody JSONObject json) {
		try {
			Integer id = json.getInteger("id");
			String saveType = json.getString("saveType");
			String path=json.getString("path");//保存路径
			
			if ("db".equals(saveType)) {
				ExcelVo excelVo = new ExcelVo();
				excelVo.setId(id);
				excelVo.setVersion(excelVoMapper.selectCount(new ExcelVo() {
					{
						setId(id);
					}
				}) + 1);
				excelVo.setContent(json.getJSONArray("content").toJSONString());
				excelVoMapper.insertSelective(excelVo);
			} else {
				String absPath=officeConfig.getOfficeRoot()+path;
//				File oldFile=new File(absPath);
//				if (oldFile.exists()) {
//					oldFile.delete();
//				}
				
				try (XSSFWorkbook workbook = ExcelUtils
						.exportLuckySheetXlsxByPOI(json.getJSONArray("content").toJSONString());
						FileOutputStream out = new FileOutputStream(absPath);) {
					workbook.write(out);
				} 
			}

			return new HashMap() {
				{
					put("code", 1);
					put("message", "保存成功!");
				}
			};
		} catch (Exception e) {
			e.printStackTrace();
			return  new HashMap() {
				{
					put("code", 0);
					put("message", "保存失败");
				}
			};
		}
	}

	/**
	 * 下载前数据放入sesseion
	 * 
	 * @param json
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/downExcelPre")

	public Object downExcel(@RequestBody JSONObject json, HttpServletRequest request) throws IOException {
		request.getSession().setAttribute("downExcelPre", json.toJSONString());
		return new HashMap() {
			{
				put("code", 1);
			}
		};
	}

	/**
	 * 將在線Excel導出下載
	 * 
	 * @param exceldatas excel数据
	 * @param fileName   文件名称
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/downExcel")

	public void downExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String downExcelPre = (String) request.getSession().getAttribute("downExcelPre");
		JSONObject json = JSON.parseObject(downExcelPre);

		String exceldatas = json.getString("content");
		String fileName = json.getString("fileName");

		response.reset();
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));

		try (ByteArrayOutputStream os = new ByteArrayOutputStream();
				XSSFWorkbook workbook = ExcelUtils.exportLuckySheetXlsxByPOI(exceldatas);) {
			workbook.write(os);
			byte[] content = os.toByteArray();
			try (InputStream is = new ByteArrayInputStream(content);
					ServletOutputStream out = response.getOutputStream();
					BufferedInputStream bis = new BufferedInputStream(is);
					BufferedOutputStream bos = new BufferedOutputStream(out);) {
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
			}
		}
	}

}
